//
//  ZJOnlinePayHouseController.m
//  这家测试项目
//
//  Created by IOS_DEVELOPER on 2017/6/8.
//  Copyright © 2017年 陈志凌. All rights reserved.
//

#import "ZJOnlinePayHouseController.h"
#import "ZJChooseHouseInformationController.h"
#import "ZJHouseInformationModel.h"
#import "ZJFloorDetailModel.h"
#import "ZJRoomModel.h"
#import "ZJHousePreselectionModel.h"
#import "ZJHouseInformationCell.h"
#import "ZJDanyuanCell.h"
#import "ZJTopImgCell.h"
#import "JKCountDownLable.h"
#import "HYBCardScaleFlowLayout.h"

#import "ZJShaiXuanVC.h"
@interface ZJOnlinePayHouseController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDataSource,UICollectionViewDelegate,ZJHouseInformationCellDelegate>{
    //测试模型
     NSArray * houseInformationArr;
     ZJHousePreselectionModel *model;
    double pointX ;
    NSInteger page;
    NSInteger dateResult;
}
@property (weak, nonatomic) IBOutlet JKCountDownLable *payHouseCountDown; //倒计时

/**<模型数组>*/
@property (nonatomic,strong) NSArray *dataArr;

@property (weak, nonatomic) IBOutlet UILabel *topTitle;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionview;
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (strong, nonatomic) ZJHouseInformationModel * partitionModel;
@property (weak, nonatomic) IBOutlet UIImageView *headImg;
@property (weak, nonatomic) IBOutlet UIView *headView;
@property (strong, nonatomic) UIPageControl * pageControl;
@end

@implementation ZJOnlinePayHouseController

- (void)viewDidLoad {
    [super viewDidLoad];
    BaseNavigationController * nvc = self.navigationController;
    nvc.bakcRootView = YES;

    self.headImg.backgroundColor = [Utils colorWithHexString:allConstHexColor];
    self.payHouseCountDown.hidden = YES;
    self.topTitle.hidden = YES;
    self.headImg.hidden = YES;
    [self setupCollection];
    [self sendRequest];
   
}
-(void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:YES];

    page = 0;
}

#pragma mark - ******************请求数据
-(void)sendRequest{
    [HUD showLoading:@"加载数据中..."];
    NSDictionary *parameter = [LRNetwork requestParameter:@{}];
    NSString *url = [LRNetwork requestURL:@"cgi/project_house.php"];
    
    
    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
         self.dataArr = [ZJHouseInformationModel mj_objectArrayWithKeyValuesArray:returnValue[@"partitions"]];
        
        self.partitionModel = self.dataArr[0];
        self.title = [NSString stringWithFormat:@"%@%@",self.partitionModel.partition_name,self.partitionModel.partition_unit]?:@"在线购房";
        if (self.title.length <=0) {
            self.title =@"在线购房";
        }
        
        NSArray * arr = self.partitionModel.buildings;

        self.partitionModel.buildings = [ZJHousePreselectionModel mj_objectArrayWithKeyValuesArray:arr];
        
        [self initSetup];
        
        [HUD hide];
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
        [HUD showErrorMsg:errorMessage];
    } withFailureBlock:^{
        
    }];

}
-(void)setupCollection{

//    HYBCardScaleFlowLayout *layout = [[HYBCardScaleFlowLayout alloc] init];
//    
//    self.collectionview.collectionViewLayout = layout;
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //设置每个item的大小
    layout.itemSize = CGSizeMake(SCREEN_WIDTH, self.collectionview.height);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = self.dataArr.count;
    self.collectionview.collectionViewLayout = layout;
    self.collectionview.pagingEnabled = YES;
}
#pragma mark - ***初始化配置
-(void)initSetup{

    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.allowsMultipleSelectionDuringEditing = YES;
    [self.tableview registerNib:[UINib nibWithNibName:NSStringFromClass([ZJHouseInformationCell class]) bundle:nil] forCellReuseIdentifier:@"ZJHouseInformationCell"];
    [self.tableview registerNib:[UINib nibWithNibName:NSStringFromClass([ZJDanyuanCell class]) bundle:nil] forCellReuseIdentifier:@"ZJDanyuanCell"];
    
    //时间计算
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    
    dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSDate *localeDate =[dateFormat dateFromString:self.prModel.net_sale_start];
    //系统当前时间
    NSDate *nowDate = [Utils getInternetDate];
    
    dateResult = [Utils compareOneDay:nowDate withAnotherDay:localeDate];
    
    _pageControl = [[UIPageControl alloc] init];
    
    if (dateResult == -1) {
        self.payHouseCountDown.hidden = NO;
        self.topTitle.hidden = NO;
        self.headImg.hidden = NO;
        self.headView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 301);
        self.collectionview.frame = CGRectMake(0, 70, SCREEN_WIDTH, self.headView.height - 70);
        _pageControl.frame = CGRectMake((self.headView.width - 60)/2, self.headView.height - 30, 60, 20);//指定位置大小
        self.collectionview.sd_layout.leftSpaceToView(self.headView, 0).topSpaceToView(self.payHouseCountDown, 0).rightSpaceToView(self.headView, 0).heightIs(231);
        [self.headView setupAutoHeightWithBottomView:self.collectionview bottomMargin:8];
        
    }else{
        self.headView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 231);
        _pageControl.frame = CGRectMake((self.headView.width - 60)/2, self.headView.height - 30, 60, 20);//指定位置大小
        self.collectionview.sd_layout.leftSpaceToView(self.headView, 0).topSpaceToView(self.headView, 0).rightSpaceToView(self.headView, 0).heightIs(231);
        [self.headView setupAutoHeightWithBottomView:self.collectionview bottomMargin:8];
    }

    [self.payHouseCountDown countDownWithDate:localeDate];
    [self.payHouseCountDown setCountDownLableChange:^(NSDate *startTime, double time, NSString *text) {}];
    self.payHouseCountDown.formatter = @"ddd天HH小时mm分ss秒";
    
    _pageControl.currentPage = 0;//指定pagecontroll的值，默认选中的小白点（第一个）
    //添加委托方法，当点击小白点就执行此方法
    
    _pageControl.pageIndicatorTintColor = RGB(247, 247, 247);// 设置非选中页的圆点颜色
    
    _pageControl.currentPageIndicatorTintColor = [Utils colorWithHexString:allConstHexColor]; // 设置选中页的圆点颜色
    
    _pageControl.numberOfPages = self.dataArr.count;//指定页面个数
    
    if (self.dataArr.count >1) {
        [self.headView addSubview:_pageControl];
    }
    
    [self.tableview reloadData];
    [self.collectionview reloadData];
    
}

#pragma mark - ***UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.partitionModel.buildings.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZJHousePreselectionModel * model1 = self.partitionModel.buildings[indexPath.row];
    
    if (model1.units.count !=1) {
        
        ZJHouseInformationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZJHouseInformationCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        cell.model = model1;
        cell.delegate = self;
        if (model1.units.count >=1) {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
        
    }else if (model1.units.count == 1){
        ZJDanyuanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZJDanyuanCell" forIndexPath:indexPath];
        cell.mainTitle.text = [NSString stringWithFormat:@"%@%@",model1.building_name,model1.building_unit];
        cell.jumpBtn.tag = indexPath.row;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        [cell.jumpBtn addTarget:self action:@selector(junmBtn:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
        
    }else if (self.partitionModel.buildings.count == 1){
        ZJDanyuanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZJDanyuanCell" forIndexPath:indexPath];
        cell.mainTitle.text = [NSString stringWithFormat:@"%@(独栋)",self.partitionModel.partition_name?:self.prModel.project_name];
        cell.jumpBtn.tag = indexPath.row;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        [cell.jumpBtn addTarget:self action:@selector(junmBtn:) forControlEvents:UIControlEventTouchUpInside];

        return cell;
    }
    
    else return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ZJHousePreselectionModel *model1 = self.partitionModel.buildings[indexPath.row];
    
    if (model1.units.count >1) {
        
        CGFloat height = [self.tableview cellHeightForIndexPath:indexPath model:model1 keyPath:@"model" cellClass:[ZJHouseInformationCell class] contentViewWidth:[Utils cellContentViewWith]];
        
        return height;
        
    }else if (model1.units.count <=1){
        
        return 75;
        
    }else return 0;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ZJHousePreselectionModel * model1 = self.partitionModel.buildings[indexPath.row];
    if (model1.units.count <1) {
        [HUD showMsg:@"暂无房源信息"];
    }
}

-(void)junmBtn:(UIButton *)sender{
    ZJChooseHouseInformationController *vc = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"ZJChooseHouseInformationController"];
    
    ZJHousePreselectionModel *model1 = self.partitionModel.buildings[sender.tag];
    ZJFloorDetailModel * model2 = [ZJFloorDetailModel mj_objectWithKeyValues:model1.units[0]];
    
    vc.unModel = model2;
    vc.deModel = model1;
    vc.titleStr = [NSString stringWithFormat:@"%@%@%@%@",model1.building_name?:@"",model1.building_unit?:@"",model2.unit_name?:@"",model2.unit_unit?:@""];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZJTopImgCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZJTopImgCell"
                                                                                forIndexPath:indexPath];
    ZJHouseInformationModel * model1 = self.dataArr[indexPath.row];
    [cell.imgV sd_setImageWithURL:[NSURL URLWithString:model1.pic_url]];
    
    return cell;
}
#pragma mark -UIScrollView代理
/**
 *  滚动视图停下来,修改页面控件的小点（页数）
 */
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UITableView class]]) {
        return;
    }
    //计算页数
     page = 0;
 
    if (scrollView.contentOffset.x == 0) {
        
        page = 0;
        
    }else{
        
        static dispatch_once_t justDoOnce;
        dispatch_once(&justDoOnce, ^{
            
            pointX = scrollView.contentOffset.x;
        });
        
        page = scrollView.contentOffset.x / pointX;
    }

//    NSLog(@"%d",page);
    
    if (page < 0 || page >99) {
        pointX = scrollView.contentOffset.x;
        page = scrollView.contentOffset.x / pointX;
    }
    
    self.partitionModel = self.dataArr[page];
    NSArray * arr = self.partitionModel.buildings;
    
    self.partitionModel.buildings = [ZJHousePreselectionModel mj_objectArrayWithKeyValuesArray:arr];
    self.title = [NSString stringWithFormat:@"%@%@",self.partitionModel.partition_name,self.partitionModel.partition_unit]?:@"在线购房";
    _pageControl.currentPage = page;
    [self.tableview reloadData];
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
}

-(void)onClikFmodel:(ZJFloorDetailModel *)Fmodel{
    NSLog(@"%@",[NSString stringWithFormat:@"%@%@-%@%@",Fmodel.partition_name,Fmodel.building_name,Fmodel.unit_name,Fmodel.unit_unit]);
    
    ZJChooseHouseInformationController *vc = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"ZJChooseHouseInformationController"];
    
    ZJHousePreselectionModel * deModel = [[ZJHousePreselectionModel alloc]init];
    
    for (ZJHouseInformationModel * model1 in self.dataArr) {
        NSArray * arr1 = [ZJHousePreselectionModel mj_objectArrayWithKeyValuesArray:model1.buildings];
        for (ZJHousePreselectionModel * model2 in arr1) {
            NSArray * arr2 = [ZJFloorDetailModel mj_objectArrayWithKeyValuesArray:model2.units];
            for (ZJFloorDetailModel * model3 in arr2) {
                if ([model3.unit_id isEqualToString:Fmodel.unit_id]) {
                    deModel = model2;
                }
            }
        }
    }
    vc.deModel = deModel;
    vc.unModel = Fmodel;
    vc.titleStr = [NSString stringWithFormat:@"%@%@%@%@",deModel.building_name?:@"",deModel.building_unit?:@"",Fmodel.unit_name?:@"",Fmodel.unit_unit?:@""];
    
    [self.navigationController pushViewController:vc animated:YES];
}
@end
